package com.hutianao.gqgl.spring.tag;

import com.hutianao.gqgl.spring.tag.entity.DictTagEntity;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.List;

public class DataSelectProcessor extends AbstractAttributeTagProcessor {
    private static final String TEXT_ATTRIBUTE  = "dataSelect";
    private static final int PRECEDENCE = 10000;
    private static final String DESC_TAG = "select";
    protected DataSelectProcessor(String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, null, false, TEXT_ATTRIBUTE, true, PRECEDENCE, true);
    }


    @Override
    protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, AttributeName attributeName, String attributeValue, IElementTagStructureHandler structureHandler) {
        final List<DictTagEntity> list = (List<DictTagEntity>) getExpressionValue(iTemplateContext, attributeValue);
        StringBuffer out = new StringBuffer();
        for(DictTagEntity item:list){
            out.append(" <option value=\"");
            out.append(item.getDicCode());
            out.append("\" ");
            out.append(">");
            out.append(item.getDictName());
            out.append("</option>");
        }
        structureHandler.setBody(out,false);
    }

    private Object getExpressionValue(ITemplateContext iTemplateContext, String expressionString) {
        final IEngineConfiguration configuration = iTemplateContext.getConfiguration();
        final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
        // 解析expression
        final IStandardExpression expression = parser.parseExpression(iTemplateContext, expressionString);
        // 获取expression的执行结果
        return expression.execute(iTemplateContext);
    }
}